package com.naiterui.ehp.bs.consult.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.consult.vo.VideoConsultMessageListVO;
import com.tencentyun.TLSSigAPIv2;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 腾讯云即时通讯IM
 *
 * @author yangfuya
 * @version 1.0
 * @date 2021-02-25 14:28
 **/
public class ImUtil {
    private static final String APPID = ConfigUtil.getString("txcloud.im.appId");
    private static final String KEY = ConfigUtil.getString("txcloud.im.key");
    private static final String URL = ConfigUtil.getString("txcloud.im.url");
    private static final String PARAMS = ConfigUtil.getString("txcloud.im.params");
    private static final String DESTROY_GROUP = URL + "/group_open_http_svc/destroy_group";
    private static final String SEND_GROUP_MSG = URL + "/group_open_http_svc/send_group_msg";
    private static final String FORBID_SEND_MSG = URL + "/group_open_http_svc/forbid_send_msg";
    private static final String DELETE_GROUP_MEMBER = URL + "/group_open_http_svc/delete_group_member";
    private static final String CHANGE_GROUP_OWNER = URL + "/group_open_http_svc/change_group_owner";

    /**
     * 获取随机数
     *
     * @return 随机数
     */
    private static long getRandom() {
        return RandomUtil.randomInt(1, 9);
    }

    /**
     * 生成用户签名
     *
     * @param identifier 身份和用户id
     * @return 签名
     */
    public static String genUserSig(String identifier) {
        TLSSigAPIv2 apIv2 = new TLSSigAPIv2(Long.parseLong(APPID), KEY);
        return apIv2.genUserSig(identifier, 7200);
    }

    /**
     * 拼接url参数
     *
     * @param url 接口地址
     * @return String 拼接后的地址
     */
    private static String spliceUrl(String url) {
        String identifier = "administrator";
        return url + String.format(PARAMS, APPID, identifier, genUserSig(identifier), getRandom());
    }

    /**
     * 在群组中发送普通消息
     *
     * @param groupId     群组id和房间id相同
     * @param fromAccount fromAccount 指定消息发送者（选填）
     * @param msgBodyList 消息列表
     * @return 返回结果
     */
    public static String sendGroupMsg(Integer groupId, String fromAccount, List<VideoConsultMessageListVO> msgBodyList) {
        String url = spliceUrl(SEND_GROUP_MSG);
        Map<Object, Object> msg = new LinkedHashMap<>();
        msg.put("GroupId", String.valueOf(groupId));
        if (fromAccount != null) {
            msg.put("From_Account", fromAccount);
        }
        msg.put("MsgRandom", getRandom());
        JSONArray msgBodys = new JSONArray();
        msgBodyList.forEach(t -> {
            Map<Object, Object> msgBody = new LinkedHashMap<>();
            JSONObject msgContent = new JSONObject();
            msgContent.put("Text", JSONUtil.toJsonStr(t));
            msgBody.put("MsgType", "TIMTextElem");
            msgBody.put("MsgContent", msgContent);
            msgBodys.add(msgBody);
        });
        msg.put("MsgBody", msgBodys);
        return HttpUtil.post(url, JSON.toJSONString(msg));
    }

    /**
     * 解散群组
     *
     * @param groupId 群组Id
     */
    public static String destroyGroup(String groupId) {
        String url = spliceUrl(DESTROY_GROUP);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        return HttpUtil.post(url, JSONUtil.toJsonStr(jsonObject));
    }

    /**
     * 解除禁言
     *
     * @param groupId     群组id
     * @param fromAccount 指定消息发送者（选填）
     * @return
     */
    public static String forbidSendMsg(Integer groupId, String fromAccount) {
        String url = spliceUrl(FORBID_SEND_MSG);
        Map<Object, Object> msg = new LinkedHashMap<>();
        msg.put("GroupId", String.valueOf(groupId));
        if (fromAccount != null) {
            msg.put("Members_Account", Collections.singletonList(fromAccount));
            msg.put("ShutUpTime", 0);
            return HttpUtil.post(url, JSON.toJSONString(msg));
        }
        return null;
    }

    /**
     * 转让群主
     *
     * @param groupId 群组id
     * @param userId  新群主id
     * @return
     */
    public static String changeGroupWwner(Integer groupId, String userId) {
        String url = spliceUrl(CHANGE_GROUP_OWNER);
        Map<Object, Object> msg = new LinkedHashMap<>();
        msg.put("GroupId", String.valueOf(groupId));
        msg.put("NewOwner_Account", userId);
        return HttpUtil.post(url, JSON.toJSONString(msg));
    }

    /**
     * 静默删人
     *
     * @param groupId 群组id
     * @param userId  要删除的群员
     * @return
     */
    public static String deleteGroupMember(Integer groupId, String[] userId) {
        String url = spliceUrl(DELETE_GROUP_MEMBER);
        Map<Object, Object> msg = new LinkedHashMap<>();
        msg.put("GroupId", String.valueOf(groupId));
//        msg.put("Silence", 1);
        msg.put("MemberToDel_Account", userId);
        return HttpUtil.post(url, JSON.toJSONString(msg));
    }
}
